package de.upb.messerschmidt.set;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import de.upb.messerschmidt.set.entity.Location;
import de.upb.messerschmidt.set.jdo.PMF;

/**
 * This Servlet returns all {@link Room}s for a specific {@link Location}.
 * 
 * @author Tim Messerschmidt
 * 
 */
public class GetRoomServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String location = req.getParameter("location");

		PersistenceManager pm = PMF.get().getPersistenceManager();

		Query query = pm.newQuery(Location.class);
		query.setFilter("name == locationName");
		query.declareParameters("String locationName");

		try {
			List<Location> results = (List<Location>) query.execute(location);

			if (!results.isEmpty()) {
				Location result = results.get(0);
				Gson gson = new Gson();
				String json = gson.toJson(result.getRooms());
				resp.setStatus(200);
				resp.getWriter().println(URLEncoder.encode(json, "UTF-8"));
			} else {
				resp.setStatus(200);
				resp.getWriter().println("no rooms yet");
			}
		} finally {
			query.closeAll();
			pm.close();
		}
	}

}
